//
//  UIButton+Category.m
//  OCDemo
//
//  Created by zhumuzhi on 2022/1/5.
//

#import "UIButton+Category.h"
#import <objc/runtime.h>

@interface UIControl()

@property (nonatomic, assign) NSTimeInterval acceptEventTime;

@end

@implementation UIButton (Category)

static const char *UIControl_acceptEventInterval = "UIControl_acceptEventInterval";
static const char *UIControl_acceptEventTime = "UIControl_acceptEventTime";

#pragma mark - 设置背景颜色

- (void)setBackgroundColor:(UIColor *)backgroundColor forState:(UIControlState)state {
    [self setBackgroundImage:[UIImage imageWithColor:backgroundColor] forState:state];
}


#pragma mark - 设置倒计时时间

- (void)startCountdown:(NSUInteger)seconds {
    [self startCountdown:seconds endBlock:^{
        
    }];
}

- (void)startCountdown:(NSUInteger)seconds endBlock:( CountdownEndBlock)endBlock {
    //倒计时代码
    __block NSUInteger timeout = seconds; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){
            //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                self.enabled = YES;
                NSString *originalTitle = [self titleForState:UIControlStateNormal];
                UIImage *originalImage = [self backgroundImageForState:UIControlStateNormal];
                UIColor *titleColor = [self titleColorForState:UIControlStateNormal];
                //设置界面的按钮显示 根据自己需求设置
                [self setTitle:originalTitle forState:UIControlStateNormal];
                [self setTitleColor:titleColor forState:UIControlStateNormal];
                [self setBackgroundImage:originalImage forState:UIControlStateNormal];
                if (endBlock) {
                    endBlock();
                }
            });
        }else{
            //倒计时执行时
            int residueSeconds = ((int)timeout/10)*10 + timeout % 10;
            dispatch_async(dispatch_get_main_queue(), ^{
                self.enabled = NO;
                UIImage *originalImage = [self backgroundImageForState:UIControlStateDisabled];
                UIColor *titleColor = [self titleColorForState:UIControlStateDisabled];
                //设置界面的按钮显示 根据自己需求设置
                [self setTitle:[NSString stringWithFormat:@"重新发送(%d)",residueSeconds] forState:UIControlStateDisabled];
                [self setTitleColor:titleColor forState:UIControlStateDisabled];
                [self setBackgroundImage:originalImage forState:UIControlStateDisabled];
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}

#pragma mark - Runtime解决UIButton重复点击问题

- (NSTimeInterval)acceptEventInterval{
    return [objc_getAssociatedObject(self, UIControl_acceptEventInterval) doubleValue];
}

- (void)setAcceptEventInterval:(NSTimeInterval)acceptEventInterval{
    objc_setAssociatedObject(self, UIControl_acceptEventInterval, @(acceptEventInterval), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (NSTimeInterval)acceptEventTime{
    return [objc_getAssociatedObject(self, UIControl_acceptEventTime) doubleValue];
}

- (void)setAcceptEventTime:(NSTimeInterval)acceptEventTime{
    objc_setAssociatedObject(self, UIControl_acceptEventTime, @(acceptEventTime), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

+ (void)load{
    //获取着两个方法
    Method systemMethod = class_getInstanceMethod(self, @selector(sendAction:to:forEvent:));
    SEL sysSEL = @selector(sendAction:to:forEvent:);
    
    Method myMethod = class_getInstanceMethod(self, @selector(cjr_sendAction:to:forEvent:));
    SEL mySEL = @selector(cjr_sendAction:to:forEvent:);
    
    //添加方法进去
    BOOL didAddMethod = class_addMethod(self, sysSEL, method_getImplementation(myMethod), method_getTypeEncoding(myMethod));
    
    //如果方法已经存在了
    if (didAddMethod) {
        class_replaceMethod(self, mySEL, method_getImplementation(systemMethod), method_getTypeEncoding(systemMethod));
    }else{
        method_exchangeImplementations(systemMethod, myMethod);
    }
    
    //----------------以上主要是实现两个方法的互换,load是gcd的只shareinstance，果断保证执行一次
}

- (void)cjr_sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event{
    if([NSStringFromClass(self.class)isEqualToString:@"UIButton"]
       || [NSStringFromClass(self.class)isEqualToString:@"IconButton"]) {
        self.acceptEventInterval = (!self.acceptEventInterval || self.acceptEventInterval == 0) ? 0.001 : self.acceptEventInterval;
        if (NSDate.date.timeIntervalSince1970 - self.acceptEventTime < self.acceptEventInterval) {
            return;
        }
    }
    
    if (self.acceptEventInterval > 0) {
        self.acceptEventTime = NSDate.date.timeIntervalSince1970;
    }
    
    [self cjr_sendAction:action to:target forEvent:event];
}

#pragma mark - 设置渐变背景颜色

// 设置渐变背景颜色
- (UIButton *)gradientButtonWithSize:(CGSize)btnSize colorArray:(NSArray *)clrs percentageArray:(NSArray *)percent gradientType:(GradientType)type {
    UIImage *backImage = [[UIImage alloc]createImageWithSize:btnSize gradientColors:clrs percentage:percent gradientType:type];
    [self setBackgroundImage:backImage forState:UIControlStateNormal];
    return self;
}


@end
